﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Windows.Devices.Bluetooth.GenericAttributeProfile;

namespace Bluetooth
{
    public partial class Form2 : Form
    {
        Form1 f;

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            f = (Form1)Owner;
            foreach (var item in f.deviceServices)
            {
                listViewServer.Items.Add(new ListViewItem(item.gattDeviceService.Uuid.ToString())
                {
                    Tag = item
                });
            }

        }

        private void listViewServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewServer.SelectedItems.Count == 0)
            {
                return;
            }
            listViewChar.Items.Clear();
            var serverItem = listViewServer.SelectedItems[0];
            var server = (DeviceService)serverItem.Tag;

            foreach (var item in server.gattCharacteristic)
            {
                listViewChar.Items.Add(new ListViewItem(new string[] 
                { 
                    item.Uuid.ToString(), 
                    (item.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)||item.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse)).ToString(),
                    item.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read).ToString(),
                    item.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify).ToString()
                })
                {
                    Tag = item
                });
            }

           
        }

        private void writeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var charItem = listViewChar.SelectedItems[0];
            var characteristic = (GattCharacteristic)charItem.Tag;
            if(characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse) 
                || characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
            {
                //f.writeCharacteristic = characteristic;
            }
            
        }

        private void notifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var charItem = listViewChar.SelectedItems[0];
            GattCharacteristic characteristic = (GattCharacteristic)charItem.Tag;
            if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify) == true)
            {
                f.notifyCharacteristics.Add(characteristic);
                //f.notifySelectCharacteristic();
            }
        }
    }
}
